package com.example.upload;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okio.Buffer;
import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;
import okio.Source;

public class SocketActivity extends AppCompatActivity {

    private TextView mTextView;
    private TextView mFileTextView;


    private static final String TAG = "TAG";
//    private static final String HOST = "192.168.23.1";
    private static final String HOST = "10.0.2.2";
    private static final int PORT = 9999;
    private BufferedSink mSink;
    private BufferedSource mSource;
    private ExecutorService mExecutorService = null;

    private File mFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        mTextView = (TextView) findViewById(R.id.textView);
        mFileTextView = (TextView) findViewById(R.id.tv1);
        mExecutorService = Executors.newCachedThreadPool();
    }


    public void upload(View view) {
        mExecutorService.execute(new connectService());
    }

    public void pause(View view) {

    }

    public void disconnect(View view) {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }

    public void select(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*;image/*");//同时选择视频和图片
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    private class uploadService implements Runnable {
        private Source mFileSource;
        private Buffer buffer = new Buffer();

        uploadService() {
            try {
                mFileSource = Okio.source(mFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                long time = System.currentTimeMillis();
                mSink.writeUtf8(mFile.getName() + "\n");
                mSink.writeUtf8(mFile.length() + "\n");
                mSink.flush();
                for (long readCount; (readCount = mFileSource.read(buffer, 2048)) != -1; ) {
                    mSink.write(buffer, readCount);
                }
                mSink.flush();
                mFileSource.close();
                showInfo(time);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void showInfo(long time) {
        long fileLength = mFile.length();
        float t = System.currentTimeMillis() - time;
        String timeInfo = "time = " + (t / 1000.0) + "S";
        String speedInfo = "speed = " + (fileLength / t) + "KB/S";
        Log.d(TAG, timeInfo);
        Log.d(TAG, speedInfo);
        addInfoUI(timeInfo);
        addInfoUI(speedInfo);
    }


    private class connectService implements Runnable {
        @Override
        public void run() {
            try {
                long time = System.currentTimeMillis();
                Socket socket = new Socket(HOST, PORT);
                Log.e(TAG, "new socket time = " + (System.currentTimeMillis() - time));
                mSink = Okio.buffer(Okio.sink(socket));
                mSource = Okio.buffer(Okio.source(socket));
                if (socket.isConnected()) {
                    mExecutorService.execute(new uploadService());
                }
            } catch (Exception e) {
                Log.e(TAG, ("connectService:" + e.getMessage()));
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {//是否选择，没选择就不会继续
            Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
            int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            actualimagecursor.moveToFirst();
            String path = actualimagecursor.getString(actual_image_column_index);
            mFileTextView.setText(path);
            mFile = new File(path);
            addInfo("fileLength:" + mFile.length() / 1000 + "KB");
        }
    }

    private void addInfo(String info) {
        mTextView.setText(info + "\n\n" + mTextView.getText());
    }

    private void addInfoUI(final String info) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                addInfo(info);
            }
        });
    }

    /**
     * 接收服务端信息 ， 暂时不用
     */
    private void receiveMsg() {
        try {
            while (true) {
                for (String receiveMsg; (receiveMsg = mSource.readUtf8Line()) != null; ) {
                    Log.d(TAG, "receiveMsg:" + receiveMsg);
                    final String finalReceiveMsg = receiveMsg;
                    addInfoUI(finalReceiveMsg);
                }
            }
        } catch (IOException e) {
            Log.e(TAG, "receiveMsg IOException");
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            mSink.close();
            mSource.close();
            mExecutorService.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
